#include "AnaDef.h"
#include "XGLUtils.h"

Double_t ftmp(const Double_t *xx, const Double_t *par)
{
  //const Int_t nn = 2; return TMath::Power(XGLUtils::PolN(xx,par,nn),par[nn+1]);
  return XGLUtils::PolN(xx,par,2);
}

void doQvsN()
{
  TTree *tree=(TTree*)gDirectory->Get("newdraw_Tree");
  
  tree->SetAlias("rtpc","tpcsig/AliTRDdEdxUtils::QMeanTPC(pow(10,ltbg))");
  //tree->SetAlias("qth", "AliTRDdEdxUtils::Q0MeanTRDpp(TMath::Power(10,ltbg))");

  tree->SetAlias("nch", "trdnch0");
  tree->SetAlias("ncls", "trdncls0");
  tree->SetAlias("trdq", "trdQ0");

  //const TString cut("run >= 126461  && run <= 130930&& itype==2 && rtpc>0.8 && rtpc<1.2&& nch==6 && ifill==0&&  trdq >1e-12 && pid!=0");
  const TString cut("run >= 126461  && run <= 130930&& itype==2 && nch==6 && ifill==0&&  trdq >1e-12 && pid!=0");
  printf("cut: %s\n", cut.Data());

  TCanvas *craw = new TCanvas("craw"); gPad->SetLogz(); 
  TH2D *hraw=new TH2D("hraw","", 100, 0.3, 1, 200, 0, 200);
  tree->Draw(Form("ncls: AliTRDdEdxUtils::Q0MeanTRDpp(TMath::Power(10,ltbg)) >> %s", hraw->GetName()),cut);
  hraw->Draw("colz");

  TCanvas *cnor = new TCanvas("cnor"); //gPad->SetLogz(); 
  TH2D *hnor = XGLUtils::NormalHist(hraw,10,1);
  hnor->Draw("colz");

  hraw->GetXaxis()->SetRangeUser(0.45,2);
  TH1D *hamp=0, *hmpv=0, *hwid=0, *hres=0, *hchi=0;
  XGLUtils::FitSlicesY(hraw, 0x0, hamp, hmpv, hwid, hres, hchi, 50, 0, 0.99);

  Double_t pars[]={120, 0, 0};//, 0, 1};
  const Int_t npar = sizeof(pars)/sizeof(Double_t);
  XGLUtils::ChisquareFit(hmpv, ftmp, npar, pars);

  TH1D *ff = XGLUtils::DrawFunc(hmpv, ftmp, pars,"hist C", kRed);

  TFile *fout=new TFile("outQvsN.root","recreate");
  hraw->Write();
  craw->Write();
  hnor->Write();
  cnor->Write();
  hamp->Write();
  hmpv->Write();
  hwid->Write();
  hres->Write();
  hchi->Write();
  ff->Write();
  fout->Save();
  fout->Close();
}

int main(int argc, char *argv[])
{
  for(int ii=0; ii<argc; ii++){
    printf("%d: %s\n", ii, argv[ii]);
  }

  if(argc!=2){
    printf("argc!=2!\n");exit(1);
  }

  TFile::Open(argv[1]);

  //XGLUtils::SetGlobalStyle();

  doQvsN();
  return 0;
}
